package com.ruoyi.project.cwsk.channel.controller;

import java.util.List;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.security.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.service.PermissionService;
import com.ruoyi.project.cwsk.channel.domain.Channel;
import com.ruoyi.project.cwsk.channel.service.IChannelService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import redis.clients.jedis.Jedis;

/**
 * 渠道商管理Controller
 * 
 * @author songzc
 * @date 2019-12-27
 */
@Controller
@RequestMapping("/cwsk/channel")
public class ChannelController extends BaseController
{
    private String prefix = "cwsk/channel";

    @Autowired
    private IChannelService channelService;
    
    @Autowired
    private IUserService userService;
    
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PermissionService permission;

    @RequiresPermissions("cwsk:channel:view")
    @GetMapping()
    public String channel()
    {
        return prefix + "/channel";
    }

    /**
     * 查询渠道商管理列表
     */
    @RequiresPermissions("cwsk:channel:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Channel channel)
    {
        start2Page();
        if(permission.isAnyRoles("ROLE_SW,ROLE_YY,ROLE_GH")){
        	if(channel.getPromoterId()==null) {
        		channel.setPromoterId(getUserId());
            }
        }else {
			List<Long> promoterIds = super.subUids();
			//公会组长要求看到所有的渠道商
			if(permission.isAnyRoles("ROLE_GHZZ")){
				promoterIds = null;
			}
			channel.setPromoterIds(promoterIds);
		}
        List<Channel> list = channelService.selectChannelList(channel);
        return getDataTable(list);
    }

    /**
     * 导出渠道商管理列表
     */
    @RequiresPermissions("cwsk:channel:export")
    @Log(title = "渠道商管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Channel channel)
    {
        List<Channel> list = channelService.selectChannelList(channel);
        ExcelUtil<Channel> util = new ExcelUtil<Channel>(Channel.class);
        return util.exportExcel(list, "channel");
    }

    /**
     * 新增渠道商管理
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
    	User user = getSysUser();
    	mmap.put("userId", user.getUserId());
    	List<User> promoters = null;
    	if(permission.isAnyRoles("ROLE_SW")){
    		promoters=userService.findPromoter(user.getUserId());
    	}else {
    		promoters=userService.findPromoter(null);
    	}
    	if(promoters.size()<=0){
    		promoters.add(user);
    	}
    	mmap.put("promoters", promoters);
        return prefix + "/add";
    }

    /**
     * 新增保存渠道商管理
     */
    @RequiresPermissions("cwsk:channel:add")
    @Log(title = "渠道商管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Channel channel)
    {
    	
    	try {
			channel.setName(StringUtils.trim(StringUtils.replaceBlank(channel.getName())));
			channel.setAcronym(StringUtils.replaceBlank(channel.getAcronym()));
			channel.setContact(StringUtils.replaceBlank(channel.getContact()));
			channel.setMobile(StringUtils.replaceBlank(channel.getMobile()));
			channel.setQq(StringUtils.replaceBlank(channel.getQq()));
			channel.setAccountBank(StringUtils.replaceBlank(channel.getAccountBank()));
			channel.setAccountName(StringUtils.replaceBlank(channel.getAccountName()));
			channel.setAccountNumber(StringUtils.replaceBlank(channel.getAccountNumber()));
			
			int rows=channelService.insertChannel(channel);
			return toAjax(rows);
		} catch (org.springframework.dao.DuplicateKeyException e) {
			return error("渠道添加失败:渠道名称或者渠道账号重复!");
		} catch (Exception e) {
			e.printStackTrace();
			return error("渠道添加失败,请联系管理员!");
		}
    }

    /**
     * 修改渠道商管理
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
    	
    	User user = getSysUser();
    	mmap.put("userId", user.getUserId());
    	List<User> promoters = null;
    	if(permission.isAnyRoles("ROLE_SW")){
    		promoters=userService.findPromoter(user.getUserId());
    	}else {
    		promoters=userService.findPromoter(null);
    	}
    	if(promoters.size()<=0){
    		promoters.add(user);
    	}
    	mmap.put("promoters", promoters);
    	
        Channel channel = channelService.selectChannelById(id);
        mmap.put("channel", channel);
        return prefix + "/edit";
    }

    /**
     * 修改保存渠道商管理
     */
    @RequiresPermissions("cwsk:channel:edit")
    @Log(title = "渠道商管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Channel channel)
    {
    	try {
			channel.setName(StringUtils.trim(StringUtils.replaceBlank(channel.getName())));
			channel.setAcronym(StringUtils.replaceBlank(channel.getAcronym()));
			channel.setContact(StringUtils.replaceBlank(channel.getContact()));
			channel.setMobile(StringUtils.replaceBlank(channel.getMobile()));
			channel.setQq(StringUtils.replaceBlank(channel.getQq()));
			channel.setAccountBank(StringUtils.replaceBlank(channel.getAccountBank()));
			channel.setAccountName(StringUtils.replaceBlank(channel.getAccountName()));
			channel.setAccountNumber(StringUtils.replaceBlank(channel.getAccountNumber()));
			
			int rows=channelService.updateChannel(channel);
			return toAjax(rows);
		} catch (org.springframework.dao.DuplicateKeyException e) {
			return error("渠道添加失败:渠道名称或者渠道账号重复!");
		} catch (Exception e) {
			e.printStackTrace();
			return error("渠道添加失败,请联系管理员!");
		}
    }

    /**
     * 删除渠道商管理
     */
    @RequiresPermissions("cwsk:channel:remove")
    @Log(title = "渠道商管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(channelService.deleteChannelByIds(ids));
    }
    
    
    /**
     * 修改渠道商状态
     */
    @RequiresPermissions("cwsk:channel:edit")
    @Log(title = "渠道商管理", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(Channel channel)
    {
        return toAjax(channelService.changeStatus(channel));
    }
    
    /**
     * 校验渠道名称是否唯一
     */
    @PostMapping("/checkNameUnique")
    @ResponseBody
    public String checkNameUnique(Channel channel)
    {
        return channelService.checkNameUnique(channel);
    }
    
    /**
     * 校验名称缩写是否唯一
     */
    @PostMapping("/checkAcronymUnique")
    @ResponseBody
    public String checkAcronymUnique(Channel channel)
    {
    	return channelService.checkAcronymUnique(channel);
    }
}
